/*
 * Copyright © 2017-2023 TemplateFactory(xiaoymin@foxmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.github.xiaoymin.template.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.template.core.TemplateContext;
import com.github.xiaoymin.template.core.TemplateFactoryConstants;
import com.github.xiaoymin.template.factory.TemplateFactory;
import com.github.xiaoymin.template.factory.impl.AideStoreTemplateFactory;
import com.github.xiaoymin.template.factory.impl.OtsCloudTemplateFactory;
import com.github.xiaoymin.template.factory.impl.V3StoreTemplateFactory;
import com.github.xiaoymin.template.factory.impl.V4StoreTemplateFactory;
import com.github.xiaoymin.template.internel.ObjectFactory;
import com.github.xiaoymin.template.util.ClassloaderUtility;
import com.jfinal.template.Engine;
import org.apache.maven.project.MavenProject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

/***
 * 配置文件
 * @since template-engine 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/06/06 15:17
 */
public class Configuration {
    
    private File configurationFile;
    private DeveloperConfiguration developerConfiguration;
    private String baseDir;
    private MavenProject mavenProject;
    private Set<String> jdbcPaths;
    private List<Context> contexts;
    
    Logger logger = LoggerFactory.getLogger(Configuration.class);
    
    /**
     * 通过配置文件初始化
     * @param configurationFile
     */
    public Configuration(File configurationFile, MavenProject mavenProject) {
        if (!configurationFile.exists()) {
            logger.info("Template Configuration File Un Exists,FilePath:{}", configurationFile.getPath());
        }
        this.configurationFile = configurationFile;
        this.mavenProject = mavenProject;
        this.contexts = new ArrayList<>();
        this.jdbcPaths = new HashSet<>();
        this.initPlugins();
    }
    public Configuration(File configurationFile, String baseDir) {
        if (!configurationFile.exists()) {
            logger.info("Template Configuration File Un Exists,FilePath:{}", configurationFile.getPath());
        }
        this.configurationFile = configurationFile;
        this.baseDir = baseDir;
        this.contexts = new ArrayList<>();
        this.jdbcPaths = new HashSet<>();
        this.initPlugins();
    }
    /**
     * 内部已实现的Plugin集合
     */
    private Map<String, TemplateFactory> innerTempaltePlugins = new HashMap<>();
    
    /**
     * 获取执行插件
     * @param aliasName
     * @return
     */
    public TemplateFactory getExecutePlugin(String aliasName) {
        return innerTempaltePlugins.get(aliasName);
    }
    
    /**
     * 当前插件是否包含
     * @param aliasName
     * @return
     */
    public boolean containtAliasName(String aliasName) {
        return innerTempaltePlugins.keySet().contains(aliasName);
    }
    
    private void initPlugins() {
        AideStoreTemplateFactory templateSwaggerModelsPlugin = new AideStoreTemplateFactory();
        OtsCloudTemplateFactory otsCloudTemplateFactory = new OtsCloudTemplateFactory();
        V3StoreTemplateFactory v3StoreTemplateFactory = new V3StoreTemplateFactory();
        V4StoreTemplateFactory v4StoreTemplateFactory = new V4StoreTemplateFactory();
        innerTempaltePlugins.put(templateSwaggerModelsPlugin.getAliasName(), templateSwaggerModelsPlugin);
        innerTempaltePlugins.put(otsCloudTemplateFactory.getAliasName(), otsCloudTemplateFactory);
        innerTempaltePlugins.put(v3StoreTemplateFactory.getAliasName(), v3StoreTemplateFactory);
        innerTempaltePlugins.put(v4StoreTemplateFactory.getAliasName(), v4StoreTemplateFactory);
    }
    
    public void addPlugin(TemplateFactory templateEnginePlugin) {
        innerTempaltePlugins.put(templateEnginePlugin.getAliasName(), templateEnginePlugin);
    }
    
    /**
     * 开始解析Xml文件
     */
    public void parse() {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(this.configurationFile);
            Element rootElement = document.getRootElement();
            if (StrUtil.equals(rootElement.getName(), TemplateFactoryConstants.ROOT_CONFIG_NAME)) {
                List<Node> nodeList = document.selectNodes("//" + TemplateFactoryConstants.ROOT_CONFIG_NAME + "/jdbcPathLocation");
                applyJdbcPaths(nodeList);
                applyDeveloperConfiguration(document);
                applyContext(document);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 初始化开发者信息
     * @param document
     */
    private void applyDeveloperConfiguration(Document document) {
        Element element = document.getRootElement().element("developerConfiguration");
        if (element != null) {
            this.developerConfiguration = new DeveloperConfiguration(element.attributeValue("name"), element.attributeValue("email"));
        } else {
            this.developerConfiguration = DeveloperConfiguration.defaultDeveloper();
        }
    }
    /**
     * 解析JDBC路径
     * @param nodeList
     */
    private void applyJdbcPaths(List<Node> nodeList) {
        if (CollectionUtil.isNotEmpty(nodeList)) {
            Node node = nodeList.get(0);
            String jdbcPathLocation = node.getStringValue();
            logger.info("jdbcPathLocation:{}", jdbcPathLocation);
            jdbcPaths.add(jdbcPathLocation);
        }
    }
    
    /**
     * 解析Context
     * @param document
     */
    private void applyContext(Document document) {
        Iterator<Element> contextElements = document.getRootElement().elementIterator("context");
        if (contextElements != null) {
            while (contextElements.hasNext()) {
                Element contextEle = contextElements.next();
                String id = contextEle.attributeValue("id");
                System.out.println(id);
                Context context = new Context(id);
                context.applyJdbcConfiguration(contextEle);
                context.applyTemplates(contextEle, this);
                contexts.add(context);
            }
        }
    }
    
    public void execute() {
        logger.info("开始生成");
        Engine templateEngine = Engine.use();
        templateEngine.setDevMode(true);
        templateEngine.setToClassPathSourceFactory();
        if (CollectionUtil.isNotEmpty(jdbcPaths)) {
            ClassLoader classLoader = ClassloaderUtility.getCustomClassloader(jdbcPaths);
            ObjectFactory.addExternalClassLoader(classLoader);
        }
        for (Context context : this.contexts) {
            // 开始初始化JDBC连接,获取表结构
            context.initJdbcConnections();
            List<TemplateFactoryConfiguration> templateConfigurations = context.getTemplateConfigurations();
            if (CollectionUtil.isNotEmpty(templateConfigurations)) {
                for (TemplateFactoryConfiguration templateConfiguration : templateConfigurations) {
                    TemplateFactory executorPlugin = getExecutePlugin(templateConfiguration.getAlias());
                    TemplateContext templateContext = new TemplateContext();
                    templateContext.setConfiguration(this);
                    templateContext.setBaseDir(this.mavenProject == null ? this.baseDir : this.mavenProject.getBasedir().getAbsolutePath());
                    templateContext.setIntrospectedTable(context.filterByName(templateConfiguration.getTableName()));
                    templateContext.setTemplateFactoryConfiguration(templateConfiguration);
                    executorPlugin.apply(templateContext);
                }
            }
        }
        
    }
    
    public DeveloperConfiguration getDeveloperConfiguration() {
        return developerConfiguration;
    }
    
    public MavenProject getMavenProject() {
        return mavenProject;
    }
}
